import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/vehicle_info_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class VehicleInfoController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  String driverId = "";
  String motorcadeId = "";
  List<VehicleInfoItem> vehicleList = [];
  int page = 1;

  void initData(String driverId, String motorcadeId) {
    this.driverId = driverId;
    this.motorcadeId = motorcadeId;
    getVehicleInfo();
  }

  Future<void> onRefresh() async {
    page = 1;
    getVehicleInfo();
  }

  Future<void> onLoading() async {
    getVehicleInfo();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getVehicleInfo();
  }

  void getVehicleInfo() {
    httpManager.post(
      Get.context,
      HttpAddress.GET_DRIVER_DETAILS_BIND_VEHICLE_LIST,
      {"id": driverId},
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        VehicleInfoEntity vehicleInfoEntity = VehicleInfoEntity().fromJson(data);
        List<VehicleInfoItem> list = vehicleInfoEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            vehicleList.clear();
            refreshController.refreshCompleted();
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            vehicleList.clear();
          }
          vehicleList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  Future<void> goToBindVehiclePage() async {
    dynamic data = await Get.toNamed(Routes.bindVehicle, arguments: {
      Constant.PARAM_DRIVER_ID: driverId,
      Constant.PARAM_MOTORCADE_ID: motorcadeId,
    });
    if (data != null) {
      page = 1;
      multiState = MultiState.loading;
      update();
      getVehicleInfo();
    }
  }

  void goToVehicleDetails(String? id) {
    Get.toNamed(Routes.vehicleDetails, arguments: id);
  }

  void unboundVehicle(String? vehicleId) {
    httpManager.post(
      Get.context,
      HttpAddress.UNBOUND_DRIVER_VEHICLE,
      {
        "driverId": driverId,
        "vehicleIds": [vehicleId]
      },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("解绑失败");
            return;
          }
          ToastUtils.toast("解绑成功");
          vehicleList.removeWhere((element) {
            return element.id == vehicleId;
          });
          if (vehicleList.isNotEmpty) {
            multiState = MultiState.success;
            update();
          } else {
            page = 1;
            multiState = MultiState.loading;
            update();
            getVehicleInfo();
          }
        }
      },
    );
  }

  String getUnboundWarn() {
    if (vehicleList.isEmpty) {
      return "";
    }
    if (vehicleList.length > 1) {
      return "是否解绑该车辆?";
    }
    if (motorcadeId.isNotEmpty) {
      return "解绑后，司机授权车辆为本车队所有车辆";
    }
    return "解绑后，司机授权车辆为本公司所有车辆";
  }
}
